/**
 * @namespace Bookmark.view.ListController
 * @author burning <www.cafeinit.com>
 * @version 2018.12.11
 */

import { PureComponent } from 'react'

class ListController extends PureComponent {
  state = {
    page: 1,
    limit: 10,
    list: [],
    searchFormValues: {},
    action: '',
    index: 0,
    editFormTitle: 'Create Bookmark',
    editFormVisible: false,
    editFormValues: {}
  }

  initData() {
    const list = [
      { id: 1, title: 'test', description: 'description', url: 'https://www.bing.com/'},
      { id: 2, title: 'test', description: 'description', url: 'https://www.bing.com/' },
      { id: 3, title: 'test', description: 'description', url: 'https://www.bing.com/' },
    ]
    this.setState({ list })
  }

  create(item) {
    const { list } = this.state
    item.id = Date.now()
    list.push(item)
    this.setState({ list })
  }

  update(index, item) {
    const list = [ ...this.state.list ]
    list[index] = { ...list[index], ...item }
    this.setState({ list })
  }

  handleCreateItem = () => {
    // console.log('handleCreateItem')
    this.setState({
      action: 'create',
      index: -1,
      editFormTitle: 'Create Bookmark',
      editFormVisible: true,
      editFormValues: {}
    })
  }
  
  handleEditItem = (index, item) => {
    // console.log('handleEditItem', index, item)
    this.setState({
      action: 'edit',
      index: index,
      editFormTitle: 'Edit Bookmark',
      editFormVisible: true,
      editFormValues: { ...item }
    })
  }

  handleEditFormOnCancel = () => {
    this.setState({ editFormVisible: false })
  }

  handleEditFormOnSave = data => {
    const { action, index } = this.state
    console.log('handleEditFormOnSave', action, index, data)
    if (action === 'create') {
      this.create(data)
    } else {
      this.update(index, data)
    }
    this.setState({
      action: '',
      editFormVisible: false
    })
  }
}

export default ListController
